package com.tarena.lbs.activity.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.dao.mapper.ActivityMapper;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.base.protocol.pager.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Repository
public class ActivityRepositoryImpl implements ActivityRepository {

    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public PageResult<ActivityVO> pageList(ActivityQuery query) {
        try {
            // 使用PageHelper进行分页
            PageHelper.startPage(query.getPageNo(), query.getPageSize());

            // 构建查询条件
            QueryWrapper<ActivityPO> queryWrapper = new QueryWrapper<>();

            // 1. 活动名称 - 模糊查询
            if (query.getActivityName() != null && !query.getActivityName().isEmpty()) {
                queryWrapper.like("activity_name", query.getActivityName());
            }

            // 2. 活动类型
            if (query.getType() != null) {
                queryWrapper.eq("activity_type", query.getType());
            }

            // 3. 活动渠道
            if (query.getChannelType() != null) {
                queryWrapper.eq("channel_type", query.getChannelType());
            }

            // 4. 活动状态
            if (query.getStatus() != null) {
                queryWrapper.eq("status", query.getStatus());
            }

            // 5. 营销方式
            if (query.getMarketingType() != null) {
                queryWrapper.eq("marketing_type", query.getMarketingType());
            }

            // 6. 活动时间范围
            if (query.getStartDate() != null && !query.getStartDate().isEmpty()) {
                queryWrapper.ge("start_date", query.getStartDate());
            }
            if (query.getEndDate() != null && !query.getEndDate().isEmpty()) {
                queryWrapper.le("end_date", query.getEndDate());
            }

            // 使用activity_status字段进行过滤，只显示activity_status=1的活动
            queryWrapper.eq("activity_status", 1);

            // 按创建时间倒序排列
            queryWrapper.orderByDesc("create_at");

            // 执行查询
            List<ActivityPO> activityPOList = activityMapper.selectList(queryWrapper);

            // 获取分页信息
            PageInfo<ActivityPO> pageInfo = new PageInfo<>(activityPOList);

            // 转换为VO列表
            List<ActivityVO> activityVOList = new ArrayList<>();
            if (activityPOList != null && !activityPOList.isEmpty()) {
                for (ActivityPO activityPO : activityPOList) {
                    ActivityVO activityVO = new ActivityVO();
                    BeanUtils.copyProperties(activityPO, activityVO);
                    // 处理类型转换问题
                    if (activityPO.getId() != null) {
                        activityVO.setId(activityPO.getId().intValue());
                    }
                    activityVOList.add(activityVO);
                }
            }

            // 构建返回结果
            PageResult<ActivityVO> pageResult = new PageResult<>();
            pageResult.setObjects(activityVOList);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setPageNo(query.getPageNo());
            pageResult.setPageSize(query.getPageSize());
            return pageResult;
        } catch (Exception e) {
            log.error("查询活动列表失败", e);
            throw new RuntimeException("查询活动列表失败", e);
        }
    }

    @Override
    public void saveActivity(ActivityAddParam param, String startDate, String endDate) {
        try {
            log.info("Repository层保存活动，参数: {}, startDate: {}, endDate: {}", param, startDate, endDate);
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ActivityPO activityPO = new ActivityPO();
            BeanUtils.copyProperties(param, activityPO);
            
            // 设置日期
            if (startDate != null && !startDate.isEmpty()) {
                activityPO.setStartDate(sdf.parse(startDate));
            }
            if (endDate != null && !endDate.isEmpty()) {
                activityPO.setEndDate(sdf.parse(endDate));
            }
            
            // 处理ID类型转换
            if (param.getId() != null) {
                activityPO.setId(Long.valueOf(param.getId()));
            }
            
            // 处理优惠券ID类型转换
            if (param.getRewardCouponId() != null) {
                activityPO.setRewardCouponId(String.valueOf(param.getRewardCouponId()));
            }
            
            // 设置商家ID - 如果参数中没有提供，则使用当前登录商家ID
            if (activityPO.getBusinessId() == null) {
                // 从认证上下文中获取当前登录的商家ID
                com.tarena.lbs.common.principle.UserPrinciple userPrinciple = 
                    com.tarena.lbs.common.utils.AuthenticationContextUtils.get();
                if (userPrinciple != null && userPrinciple.getRole() != null) {
                    // 检查是否为商家角色
                    if ("SHOP".equals(userPrinciple.getRole().name())) {
                        activityPO.setBusinessId(userPrinciple.getId());
                    }
                }
                
                // 如果仍然没有获取到businessId，则使用默认值
                if (activityPO.getBusinessId() == null) {
                    activityPO.setBusinessId(1); // 临时设置默认商家ID
                }
            }
            
            // 设置时间和默认值
            Date now = new Date();
            if (param.getId() == null) {
                // 新增操作
                activityPO.setCreateAt(now);
                activityPO.setUpdateAt(now);
                activityPO.setStatus(0); // 未开始
                activityPO.setEnableStatus(1); // 启用
                activityPO.setActivityType(1); // 默认赠领类型
                
                // 设置默认的奖励类型为1（如果没有设置的话）
                if (activityPO.getRewardType() == null) {
                    activityPO.setRewardType(1); // 默认奖励类型
                }
                
                // 设置活动状态为1（未删除状态）
                if (activityPO.getActivityStatus() == null) {
                    activityPO.setActivityStatus(1); // 未删除状态
                }
                
                // 插入数据
                activityMapper.insert(activityPO);
                log.info("新增活动成功，ID: {}", activityPO.getId());
            } else {
                // 更新操作
                activityPO.setUpdateAt(now);
                
                // 更新数据
                activityMapper.updateById(activityPO);
                log.info("更新活动成功，ID: {}", param.getId());
            }
        } catch (ParseException e) {
            log.error("日期转换失败，startDate: {}, endDate: {}, error: {}", startDate, endDate, e.getMessage(), e);
            throw new RuntimeException("日期格式错误", e);
        } catch (Exception e) {
            log.error("保存活动失败，参数: {}, error: {}", param, e.getMessage(), e);
            throw new RuntimeException("保存活动失败", e);
        }
    }

    @Override
    public ActivityVO getActivityById(Integer id) {
        try {
            ActivityPO activityPO = activityMapper.selectById(Long.valueOf(id));
            if (activityPO != null) {
                ActivityVO activityVO = new ActivityVO();
                BeanUtils.copyProperties(activityPO, activityVO);
                // 处理类型转换
                if (activityPO.getId() != null) {
                    activityVO.setId(activityPO.getId().intValue());
                }
                // 处理优惠券ID转换
                if (activityPO.getRewardCouponId() != null) {
                    try {
                        activityVO.setRewardCouponId(String.valueOf(Integer.parseInt(activityPO.getRewardCouponId())));
                    } catch (NumberFormatException e) {
                        log.warn("优惠券ID格式错误: {}", activityPO.getRewardCouponId());
                    }
                }
                return activityVO;
            }
            return null;
        } catch (Exception e) {
            log.error("查询活动详情失败，活动ID：{}", id, e);
            throw new RuntimeException("查询活动详情失败", e);
        }
    }
    
    // 2. 修改deleteActivity方法中的假删除逻辑，使用activity_status字段
    @Override
    public void deleteActivity(Integer id) {
        try {
            log.info("Repository层删除活动，ID: {}", id);
            // 执行假删除操作 - 修改activity_status字段为0
            ActivityPO activityPO = new ActivityPO();
            activityPO.setId(Long.valueOf(id));
            activityPO.setActivityStatus(0); // 修改为使用activityStatus字段，表示删除状态
            activityPO.setUpdateAt(new Date()); // 更新时间
            
            activityMapper.updateById(activityPO);
            log.info("删除活动成功，ID: {}", id);
        } catch (Exception e) {
            log.error("删除活动失败，ID: {}", id, e);
            throw new RuntimeException("删除活动失败", e);
        }
    }

    @Override
    public void updateActivityStatus(Integer id, Integer enableStatus) {
        try {
            log.info("Repository层更新活动状态，ID: {}, enableStatus: {}", id, enableStatus);
            ActivityPO activityPO = new ActivityPO();
            activityPO.setId(Long.valueOf(id));
            activityPO.setEnableStatus(enableStatus); // 设置新的状态值
            activityPO.setUpdateAt(new Date()); // 更新时间

            activityMapper.updateById(activityPO);
            log.info("更新活动状态成功，ID: {}, enableStatus: {}", id, enableStatus);
        } catch (Exception e) {
            log.error("更新活动状态失败，ID: {}, enableStatus: {}", id, enableStatus, e);
            throw new RuntimeException("更新活动状态失败", e);
        }
    }
}